package cn.nubia.admin.common.http;

import cn.nubia.admin.common.springmvc.WebContext;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by wangj on 2015/7/29.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    /**
     * 过滤掉的前缀匹配
     */
    private static final String[] whiteList = new String[]{"/doLogin.html" , "/"};
    /**
     * 需要判断的后缀
     */
    private static final String[] suffixes = new String[]{".html" , ".htm"};

    public boolean preHandle(HttpServletRequest httpRequest, HttpServletResponse response, Object handler){
        for (String prefix : whiteList) {
            if (httpRequest.getRequestURI().equals(prefix)) {
                return true;
            }
        }

        boolean exist = false;
        for (String suffix : suffixes) {
            if (!httpRequest.getRequestURI().endsWith(suffix)) {
                exist = true;
            }
        }
        if (!exist) {
            return true;
        }

        if (WebContext.getCachedUser() == null){
            try {
                response.sendRedirect("/");
                return false;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}
